import urllib, json, re, urlparse


def urlEncodeNonAscii(b):
    return re.sub('[\x80-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b)


def iriToUri(iri):
    parts = urlparse.urlparse(iri)
    return urlparse.urlunparse(
        part.encode('idna') if parti == 1 else urlEncodeNonAscii(part.encode('utf-8'))
        for parti, part in enumerate(parts)
    )


def twitterGetSearch(term, geocode, page, per_page, result_type):
    url = "http://search.twitter.com/search.json?result_type=" + result_type + "&rpp=" + per_page + "&page=" + page + "&q=" + term + "&geocode=" + geocode
    url = iriToUri(url)
    return json.load(urllib.urlopen(url))


def getGeoCode(addr):
    if addr <> '':
        url = ''
        geocode = ''
        #       parse
        if addr[0] == '(':
            center = addr.replace('(', '').replace(')', '')
            lat, lng = center.split(',')
            url = 'http://maps.google.com/maps?q=%s+%s' % (lat, lng)
        else:
            # Encode query string into URL
            url = 'http://maps.google.com/?q=' + urllib.quote(addr) + '&output=js'
            #print '\nQuery: %s' % (url)

            # Get XML location
            xml = urllib.urlopen(url).read()

            if '<error>' in xml:
                print '\nGoogle cannot interpret the address.'
            else:
                # Strip lat/long coordinates from XML
                lat, lng = 0.0, 0.0
                center = xml[xml.find('{center') + 10:xml.find('}', xml.find('{center'))]
                center = center.replace('lat:', '').replace('lng:', '').replace('at:', '')
                lat, lng = center.split(',')
                geocode = lat + "," + lng
        return geocode + ",1mi"
    else:
        return ""
